﻿using RabbitMQ.Client;
using RabbitMQ.Client.Framing;
using System;
using System.Collections.Generic;
using System.Text;

namespace RabbitMQProducerTester
{
    class DelayedMessageSend
    {
        public static void Send(ConnectionFactory factory)
        { 
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    IDictionary<string, object> args = new Dictionary<string, object>();
                    args.Add("x-delayed-type", "direct");
                    channel.ExchangeDeclare("DelayedExchange", "x-delayed-message", true, false, args);

                    IBasicProperties properties = new BasicProperties();
                    properties.Headers = new Dictionary<string, object>();
                    properties.Headers.Add("x-delay", 10000);//10秒钟
                    channel.QueueDeclare(queue: "delay-new",
                        durable: false,
                        exclusive: false,
                        autoDelete: false,
                        arguments: args);
                    channel.QueueBind("delay-new", "DelayedExchange", "", null);

                    string message = $"Hello World, delayedMessage {DateTime.Now}";
                    var body = Encoding.UTF8.GetBytes(message);

                    channel.BasicPublish(exchange: "DelayedExchange",
                        routingKey: "#", 
                        basicProperties: properties,
                        body: body);
                    Console.WriteLine($" [x] Sent {message} at {DateTime.Now}");
                }
            }
        }
    }
}
